package org.yray.sip.rtp.sender;


import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.RemovalListener;
import lombok.extern.slf4j.Slf4j;
import org.yray.sip.constant.Constants;
import org.yray.sip.server.SipSession;
import org.yray.sip.utils.CMG711;
import org.yray.sip.utils.G711Grabber;
import org.yray.sip.utils.IcspBeanHolder;

import java.util.concurrent.TimeUnit;

@Slf4j
public class RtRtpContext {

    private static Cache<String,RtRtpTts> rtRtpCache = Caffeine.newBuilder()
            .maximumSize(2048)
            .expireAfterWrite(Constants.CACHE_TIME, TimeUnit.SECONDS)
            .removalListener((RemovalListener<String, RtRtpTts>) (key, value, cause) ->
                    log.info( key, "RtRtpContext","删除原因:{}" ,cause.toString()))
            .build();

    public static void sendPcm(int sn,String key,byte[] wavs)
    {
        RtRtpTts rtRtpTts=rtRtpCache.get(key,v->{
                SipSession sipSession= IcspBeanHolder.getBean(ISipSessionCache.class).get(key);
               return new RtRtpTts(sipSession);});
        rtRtpTts.addWav(CMG711.encode(wavs));

    }

    public static void close(String key)
    {
        RtRtpTts rtRtpTts= rtRtpCache.getIfPresent(key);
        if(rtRtpTts!=null)
        {
            rtRtpTts.finish();
            rtRtpCache.invalidate(key);
        }
    }
}
